<template>
    <div class="schoolList pl10 pr10">
        <avue-crud
            ref="crud"
            :table-loading="loading"
            :data="data"
            :option="option"
            :permission="setBtnPermission"
            :page.sync="page"
            :search.sync="searchForm"
            :defaults.sync="defaults"
            v-model="form"
            @on-load="onLoad"
            @search-change="handleSearchChange"
            @row-save="handleAdd"
            @row-update="handleUpdate"
        >
            <!-- 自定义列 -->
            <template slot="cover" slot-scope="scope">
                <div class="media">
                    <img :src="scope.row.cover" style="width: 50px; border-radius: 3px"/>
                </div>
            </template>

            <template slot-scope="{ row }" slot="dataType">
                <el-tag v-if="row.dataType === 1" type="success">企微</el-tag>
                <el-tag v-else>钉钉</el-tag>
            </template>

            <template slot-scope="{ row }" slot="status">
                <el-tag>{{ row.status === 1 ? '正常' : '不正常' }}</el-tag>
            </template>

            <!--自定义表单-->
            <template slot-scope="{ value, type }" slot="coverForm">
                <sc-upload v-if="type === 'edit'" @on-change="selectUploadImg" :echoFileList="echoFileList"/>
                <sc-upload v-else-if="type === 'add'" @on-change="selectUploadImg"/>
                <img v-else style="width: 200px" :src="value" @click="$imgView(value)"/>
            </template>

            <template slot-scope="{ value }" slot="statusForm">
                <el-tag>{{ value === 1 ? '正常' : '不正常' }}</el-tag>
            </template>

            <!-- 自定义菜单 -->
            <template slot="menu" slot-scope="{ row }">
                <el-button icon="el-icon-view" type="text" size="mini" @click="handelView(row)">查看</el-button>
                <el-button icon="el-icon-edit" type="text" size="mini" @click="handelEdit(row)">编辑</el-button>
                <el-button type="primary" plain size="mini" @click="handelDataSynchronize(row)">企微数据同步</el-button>
                <el-button type="primary" plain size="mini" @click="updateHikSync(row)">海康学生数据同步</el-button>
            </template>
        </avue-crud>

        <!-- 弹窗 -->
        <el-dialog title="重复班级学生" :visible.sync="centerDialogVisible" width="30%" center>
            <ul class="infinite-list" style="overflow: auto; display: flex">
                <li v-for="(item, index) in cData" :key="index" style="margin-right: 15px">
                    <el-link @click="handleStudentName(item)" type="warning" size="medium">{{ item }}</el-link>
                </li>
            </ul>
            <span slot="footer" class="dialog-footer">
                <el-button @click="copyStudentNames()" type="primary">复 制</el-button>
                <el-button @click="centerDialogVisible = false">关 闭</el-button>
            </span>
        </el-dialog>

        <el-dialog title="海康存在&企微未同步学生" :visible.sync="hikDialogVisible" width="30%" center>
            <ul class="infinite-list" style="overflow: auto; display: flex">
                <li v-for="(item, index) in cData" :key="index" style="margin-right: 15px">
                    <el-link @click="handleHikStudentName(item.studentName)" type="warning" size="medium">{{ item.studentName }}</el-link>
                </li>
            </ul>
            <span slot="footer" class="dialog-footer">
                <el-button @click="copyHikStudentNames()" type="primary">复 制</el-button>
                <el-button @click="hikDialogVisible = false">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import page from 'admin/mixins/page'

const types = [
    {
        aesKey: '企微AesKey',
        agentId: '企微应用AGENT_ID',
        appId: '企微应用KEY',
        appSecret: '企微应用SECRET',
        token: 'token',
        agentAppSecret: '第三方应用SECRET',
    },
    {
        aesKey: '钉钉AesKey',
        agentId: '钉钉应用AGENT_ID',
        appId: '钉钉应用KEY',
        appSecret: '钉钉应用SECRET',
        token: 'token',
    },
]
export default {
    mixins: [page],
    name: 'SchoolList',

    data() {
        return {
            header: true,
            popup: {
                studentBatchPopup: false,
            },
            currentRow: {}, //当前选中行数据
            //分页参数
            searchForm: {},
            urls: {
                0: 'schoolConfig',
                1: 'schoolList',
                2: 'getSchoolList',
            },
            data: [],
            echoFileList: [{name: 'food.jpeg', url: 'https://img0.baidu.com/it/u=2130615794,142753515&fm=26&fmt=auto'}], //回显图片数据

            centerDialogVisible: false, //重复班级学生
            hikDialogVisible: false, //海康存在&企微未同步学生
            cData: [],
            form: {},
            defaults: {},
            rowData: {},
        }
    },
    computed: {
        option() {
            return {
                ...window.avueCrud,
                addBtn: this.btns.includes('addBtn'),
                addTitle: '添加学校信息',
                addBtnText: '添加学校信息',
                dialogWidth: '40%',
                searchGutter: 300,
                align: 'left',
                addBtn: this.isAdd,
                header: this.isAdd,
                menuWidth: 500,
                column: [
                    {
                        label: '学校',
                        prop: 'name',
                        search: true,
                        searchSpan: 4,
                        searchLabelWidth: 50,
                        row: true,
                        span: 24,
                        labelWidth: 200,
                        minWidth: 150,
                        rules: [
                            {
                                required: true,
                                message: '必填项',
                                trigger: 'blur',
                            },
                        ],
                    },

                    {
                        label: '数据类型',
                        prop: 'dataType',
                        row: true,
                        span: 24,
                        labelWidth: 200,
                        value: 1,
                        type: 'radio',
                        editDisabled: true, //编辑禁用
                        dicData: [
                            {
                                label: '企微',
                                value: 1,
                            },
                            {
                                label: '钉钉',
                                value: 2,
                            },
                        ],
                    },
                    {
                        label: '应用KEY',
                        prop: 'appId',
                        row: true,
                        display: true,
                        hide: true,
                        span: 24,
                        labelWidth: 200,
                        minWidth: 300,
                        rules: [
                            {
                                required: true,
                                message: '必填项',
                                trigger: 'blur',
                            },
                        ],
                        formatter(row, val) {
                            return row.dataProperties.appId
                        },
                    },
                    {
                        label: '第三方应用SECRET',
                        prop: 'agentAppSecret',
                        row: true,
                        hide: true,
                        span: 24,
                        labelWidth: 200,
                        minWidth: 300,
                        formatter(row, val) {
                            return row.dataProperties.aesKey || '/'
                        },
                        rules: [
                            {
                                required: true,
                                message: '必填项',
                                trigger: 'blur',
                            },
                        ],
                    },
                    {
                        label: '应用AGENT_ID',
                        prop: 'agentId',
                        display: true,
                        hide: true,
                        row: true,
                        span: 24,
                        labelWidth: 200,
                        minWidth: 300,
                        type: 'number',
                        controls: false,
                        placeholder: '请输入应用AGENT_ID，只能是数字',
                        rules: [
                            {
                                required: true,
                                message: '必填项',
                                trigger: 'blur',
                            },
                        ],
                        formatter(row, val) {
                            return row.dataProperties.agentId
                        },
                    },
                    {
                        label: '应用SECRET',
                        prop: 'appSecret',
                        display: true,
                        hide: true,
                        row: true,
                        span: 24,
                        labelWidth: 200,
                        minWidth: 300,
                        formatter(row, val) {
                            return row.dataProperties.appSecret
                        },
                    },

                    {
                        label: 'AesKey',
                        prop: 'aesKey',
                        row: true,
                        hide: true,
                        span: 24,
                        labelWidth: 200,
                        minWidth: 300,
                        display: false,
                        formatter(row, val) {
                            return row.dataProperties.aesKey || '/'
                        },
                    },
                    {
                        label: 'token',
                        prop: 'token',
                        hide: true,
                        row: true,
                        span: 24,
                        labelWidth: 200,
                        minWidth: 300,
                        display: false,
                        formatter(row, val) {
                            return row.dataProperties.token || '/'
                        },
                    },

                    {
                        label: '创建时间',
                        prop: 'createTime',
                        display: false,
                        minWidth: 140,
                    },
                    {
                        label: '更新时间',
                        prop: 'updateTime',
                        display: false,
                        minWidth: 140,
                    },
                ],
            }
        },
    },
    watch: {
        'form.dataType'(val) {
            let typeObj = types[val - 1]
            for (const key in typeObj) {
                if (Object.hasOwnProperty.call(typeObj, key)) {
                    this.defaults[key]['label'] = typeObj[key]
                }
            }

            if (val === 1) {
                // this.defaults.aesKey.display = true
                // this.defaults.token.display = true
                this.defaults.agentAppSecret.display = true
            } else {
                // this.defaults.aesKey.display = false
                // this.defaults.token.display = false
                this.defaults.agentAppSecret.display = false
            }
        },
    },
    methods: {
        // 控制按钮显隐
        setBtnPermission(key) {
            return true
            // if (this.btns.length === 0) return (this.header = false)
            // if (key === 'menu') return true
            // else if (key === 'addBtn' && this.btns.includes('addBtn')) return true
            // else if (key === 'editBtn' && this.btns.includes('editBtn')) return true
            // else if (key === 'delBtn' && this.btns.includes('delBtn')) return true
            // else if (key === 'viewBtn' && this.btns.includes('viewBtn')) return true
            // else return false
        },
        // 查看
        async handelView(row) {
            let data = JSON.parse(JSON.stringify(row))
            data = {...data, ...data.dataProperties}
            this.$refs.crud.rowView(data)
        },

        // 编辑弹窗打开之前执行
        handelEdit(row) {
            let data = JSON.parse(JSON.stringify(row))
            data = {...data, ...data.dataProperties}
            this.$refs.crud.rowEdit(data)
        },

        // 添加
        async handleAdd(form, done) {
            let dataForm = JSON.parse(JSON.stringify(form))
            let params = {
                dataProperties: {
                    aesKey: dataForm.aesKey,
                    agentId: dataForm.agentId,
                    appId: dataForm.appId,
                    appSecret: dataForm.appSecret,
                    agentAppSecret: dataForm.agentAppSecret,
                    token: dataForm.token,
                },
                name: dataForm.name,
                dataType: dataForm.dataType,
            }

            if (params.dataType === 2) {
                delete params.dataProperties.aesKey
                delete params.dataProperties.token
            }

            let {code, msg} = await this.$api.schoolConfig.schoolList.addSchool(params)
            if (code === 200) {
                this.$message.success('添加成功！' || msg)
                done()
                this.getData(this.searchForm)
            }
        },
        // 修改
        async handleUpdate(form, index, done, loading) {
            let dataForm = JSON.parse(JSON.stringify(form))
            let params = {
                dataProperties: {
                    aesKey: dataForm.aesKey,
                    agentId: dataForm.agentId,
                    appId: dataForm.appId,
                    appSecret: dataForm.appSecret,
                    agentAppSecret: dataForm.agentAppSecret,
                    token: dataForm.token,
                },
                name: dataForm.name,
                dataType: dataForm.dataType,
                id: dataForm.id,
            }

            if (params.dataType === 2) {
                delete params.dataProperties.aesKey
                delete params.dataProperties.token
            }
            this.$refs.crud.validate(async (valid) => {
                if (valid) {
                    let {code, msg} = await this.$api.schoolConfig.schoolList.updateSchool(params)
                    if (code === 200) {
                        this.$message.success('修改成功！' || msg)
                        done()
                        this.getData(this.searchForm)
                    }
                }
            })
        },

        //选择图片触发
        selectUploadImg(files) {
            console.log('files :>> ', files)
        },

        // 企微数据同步
        async handelDataSynchronize(row) {
            this.$confirm('请确认同步', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    const loading = this.$scLoading('正在同步...')
                    try {
                        let {code, msg} = await this.$api.schoolConfig.schoolList.dataSynchronize({schoolId: row.id})
                        if (code === 200) {
                            loading.close()
                            this.$message.success('同步成功！' || msg)
                        } else {
                            this.$message.error('同步失败！！！')
                            loading.close()
                        }
                    } catch (error) {
                        this.$message.error(error)
                        loading.close()
                    }
                })
                .catch(() => {
                })
        },

        // 海康数据同步
        async updateHikSync(row) {
            this.$confirm('请确认同步', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    this.rowData = row
                    const loading = this.$scLoading('正在同步...')
                    try {
                        let {data, code, msg} = await this.$api.schoolConfig.schoolList.syncHikAllStudent(row.id)
                        if (code === 200) {
                            loading.close()
                            this.$message.success(msg || '操作成功！')
                            this.hikDialogVisible = true
                            this.cData = data
                        } else {
                            this.$message.error('同步失败！！！')
                            loading.close()
                        }
                    } catch (error) {
                        this.$message.error(error)
                        loading.close()
                    }
                })
                .catch(() => {
                })
        },
        // 复制重复学生
        copyStudentNames() {
            let names = this.cData.map((v) => {
                return v
            })
            const str = `${this.rowData.schoolName}\r\n${names.join('\r\n')}`
            this.$Clipboard({
                text: str,
            })
                .then(() => {
                    this.$message.success(`复制成功`)
                })
                .catch(() => {
                    this.$message.error('复制失败')
                })
        },

        // 剪切复制
        handleStudentName(name) {
            this.$Clipboard({
                text: name,
            })
                .then(() => {
                    this.$message.success(`复制成功${name}`)
                })
                .catch(() => {
                    this.$message.error('复制失败')
                })
        },

        // 海康存在&企微未同步学生
        copyHikStudentNames() {
            let names = this.cData.map((v) => {
                return v.studentName
            })
            const str = `${this.rowData.schoolName}\r\n${names.join('\r\n')}`
            this.$Clipboard({
                text: str,
            })
                .then(() => {
                    this.$message.success(`复制成功`)
                })
                .catch(() => {
                    this.$message.error('复制失败')
                })
        },

        // 海康存在&企微未同步学生
        handleHikStudentName(name) {
            this.$Clipboard({
                text: name,
            })
                .then(() => {
                    this.$message.success(`复制成功${name}`)
                })
                .catch(() => {
                    this.$message.error('复制失败')
                })
        },
    },
}
</script>

<style lang="scss" scoped>
.schoolList {
}
</style>
